package com.linsen.erp.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.linsen.erp.admin.provider.enums.DataScopeCustomizeTypeEnum;
import com.linsen.erp.admin.entity.RoleDataScopeEntity;
import com.linsen.erp.admin.mapper.RoleDataScopeMapper;
import com.linsen.erp.admin.service.IRoleDataScopeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色-数据权限范围 服务实现类
 * </p>
 *
 * @author zhaoyong
 * @since 2024-03-27
 */
@Service
@RequiredArgsConstructor
public class RoleDataScopeServiceImpl extends ServiceImpl<RoleDataScopeMapper, RoleDataScopeEntity> implements IRoleDataScopeService {

    @Override
    public List<RoleDataScopeEntity> getByRoleId(String roleId) {
        return this.list(
                new LambdaQueryWrapper<RoleDataScopeEntity>()
                        .eq(RoleDataScopeEntity::getRoleId,roleId)
        );
    }

    @Transactional
    @Override
    public void set(String roleId, List<String> roleDataScopeDeptIdList, List<String> roleDataScopeUserIdList) {
        //清除原有设置
        this.remove(
                new LambdaQueryWrapper<RoleDataScopeEntity>()
                        .eq(RoleDataScopeEntity::getRoleId,roleId)
        );

        if (ObjectUtil.isNotEmpty(roleDataScopeDeptIdList)){
            List<RoleDataScopeEntity> roleMenuEntityList = roleDataScopeDeptIdList.stream().map(deptId -> {
                RoleDataScopeEntity roleDataScopeEntity = new RoleDataScopeEntity();
                roleDataScopeEntity.setRoleId(roleId);
                roleDataScopeEntity.setType(DataScopeCustomizeTypeEnum.DEPT.getValue());
                roleDataScopeEntity.setDataId(deptId);
                return roleDataScopeEntity;
            }).collect(Collectors.toList());

            this.saveBatch(roleMenuEntityList);
        }

        if (ObjectUtil.isNotEmpty(roleDataScopeUserIdList)){
            List<RoleDataScopeEntity> roleMenuEntityList = roleDataScopeUserIdList.stream().map(userId -> {
                RoleDataScopeEntity roleDataScopeEntity = new RoleDataScopeEntity();
                roleDataScopeEntity.setRoleId(roleId);
                roleDataScopeEntity.setType(DataScopeCustomizeTypeEnum.USER.getValue());
                roleDataScopeEntity.setDataId(userId);
                return roleDataScopeEntity;
            }).collect(Collectors.toList());

            this.saveBatch(roleMenuEntityList);
        }
    }
}
